<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class BillExport extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id',
        'book_id',
        'title',
        'export_range',
        'start_date',
        'end_date',
        'format',
        'status',
        'file_path',
        'expires_at',
        'error_message',
        'download_token',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'expires_at' => 'datetime',
    ];

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 关联账本
     */
    public function book()
    {
        return $this->belongsTo(MoneyBook::class, 'book_id');
    }

    /**
     * 检查文件是否已过期
     */
    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    /**
     * 获取下载URL
     */
    public function getDownloadUrl()
    {
        if ($this->status !== 'completed' || !$this->file_path || $this->isExpired()) {
            return null;
        }
        
        return route('bill-export.download', $this->id);
    }

    /**
     * 获取公开下载URL
     */
    public function getPublicDownloadUrl()
    {
        if ($this->status !== 'completed' || !$this->file_path || $this->isExpired()) {
            return null;
        }
        
        // 如果没有下载token，生成一个
        if (!$this->download_token) {
            $this->generateDownloadToken();
        }
        
        return route('public.download', $this->download_token);
    }

    /**
     * 生成下载token
     */
    public function generateDownloadToken()
    {
        $this->download_token = bin2hex(random_bytes(32));
        $this->save();
        return $this->download_token;
    }

    /**
     * 获取状态文本
     */
    public function getStatusText()
    {
        $statusMap = [
            'pending' => '等待处理',
            'processing' => '处理中',
            'completed' => '已完成',
            'failed' => '失败',
            'expired' => '已过期'
        ];
        
        return $statusMap[$this->status] ?? '未知状态';
    }

    /**
     * 获取剩余时间文本
     */
    public function getRemainingTimeText()
    {
        if (!$this->expires_at || $this->isExpired()) {
            return null;
        }
        
        $now = now();
        $diff = $this->expires_at->diff($now);
        
        if ($diff->days > 0) {
            return $diff->days . '天';
        } elseif ($diff->h > 0) {
            return $diff->h . '小时';
        } else {
            return $diff->i . '分钟';
        }
    }

    /**
     * 标记为过期
     */
    public function markAsExpired()
    {
        $this->update([
            'status' => 'expired',
            'expires_at' => now(),
        ]);

        // 删除文件
        if ($this->file_path && Storage::exists($this->file_path)) {
            Storage::delete($this->file_path);
        }
    }

    /**
     * 获取格式文本
     */
    public function getFormatText()
    {
        $formatMap = [
            'excel' => 'Excel (.xlsx)',
            'csv' => 'CSV (.csv)',
            'pdf' => 'PDF (.pdf)'
        ];
        
        return $formatMap[$this->format] ?? '未知格式';
    }
}